package com.sale.common.mybatis.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.redis.utils.RedisUtils;
import com.sale.common.satoken.utils.LoginHelper;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 多租户处理插件
 * @Date 23-07-10
 * @Author hl
 **/
public class CustomTenantLineHandler implements TenantLineHandler {
    /**
     * 忽略添加租户ID的表
     */
/*
    private final static List<String> IGNORE_TABLE_NAMES = Lists.newArrayList(
        "t_country","sys_accounting","sys_accounts","sys_user_accounts","sys_role","sys_workbench","sys_role_dept","sys_role_menu","sys_dept","sys_role_warehouse",
        "t_language", "sys_dict_data", "sys_dict_type","undo_log","sys_logininfor","sys_oper_log","sys_menu","sys_root","sys_user_role","sys_functional_parameter","sys_inventory_accounting","sys_parameter_description","sys_accounting_detail","sys_parameter_description"
    );
*/

    private final static List<String> IGNORE_TABLE_NAMES = new ArrayList<>(Arrays.asList(
        "t_country","sys_accounting","sys_config","sys_accounts","sys_user_accounts","sys_role","sys_workbench","sys_role_dept","sys_role_menu","sys_dept","sys_role_warehouse",
        "t_language","sys_oss_config" ,"sys_dict_data", "strategy_message","sys_dict_type","undo_log","sys_logininfor","sys_oper_log","sys_menu","sys_root","sys_user_role","sys_functional_parameter","sys_inventory_accounting","sys_parameter_description","sys_accounting_detail","sys_parameter_description"
    ));

    /**
     * 获取租户ID值表达式(可从cookie、token、缓存中取)
     *
     * @return
     */
    @Override
    public Expression getTenantId() {
        String userIdStr = LoginHelper.getUserIdStr();
        if (StringUtils.isBlank(userIdStr)) {
            return new StringValue("");
        }
        String tenantId = RedisUtils.getCacheObject(userIdStr);
        if (StringUtils.isBlank(tenantId)) {
            return new StringValue("");
        }
        return new StringValue(tenantId);
    }


    /**
     * 获取租户字段名(数据库的租户ID字段名)
     *
     * @return
     */
    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }


    /**
     * 根据表名判断是否忽略拼接多租户条件
     *
     * @param tableName
     * @return
     */
    @Override
    public boolean ignoreTable(String tableName) {
        String userIdStr = LoginHelper.getUserIdStr();
        if (StringUtils.isBlank(userIdStr)) {
            //如果未初始化到，不拼接租户id
            return true;
        }
        return IGNORE_TABLE_NAMES.contains(tableName);
    }
}
